<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false"></el-alert>
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader
                        v-model="selectedKeys"
                        :options="cateList"
                        :props="cascaderProp"
                        @change="handleChange"
                        clearable>
                    </el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" :disabled="isBtnDisabled"
                    @click="addFormShow">添加参数</el-button>
                    <el-table border stripe style="width: 100%" :data="manyTableData">
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                                <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" width="300px">
                            <template slot-scope="scope">
                                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditVisble(scope.row.attr_id)">编辑</el-button>
                                    <el-button type="danger" icon="el-icon-delete" size="mini"
                                    @click="deteleParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" :disabled="isBtnDisabled"  @click="addFormShow">添加属性</el-button>
                    <el-table border stripe style="width: 100%" :data="onlyTableData">
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">{{item}}</el-tag>
                                <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm(scope.row)"
                                @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" width="300px">
                            <template slot-scope="scope">
                                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditVisble(scope.row.attr_id)">编辑</el-button>
                                    <el-button type="danger" icon="el-icon-delete" size="mini"
                                    @click="deteleParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加分类 -->
        <el-dialog :title="'添加'+ titleText" :visible.sync="addDialogFormVisible" @close="addFormClose">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="addDialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
        </div>
        </el-dialog>
        <!-- 修改分类 -->
        <el-dialog :title="'修改'+ titleText" :visible.sync="editDialogFormVisible" @close="editFormClose">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="editDialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
        </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            cateList:[],
            selectedKeys:[],
            cascaderProp:{
                value: 'cat_id',
                label: 'cat_name',
                children: 'children',
                expandTrigger: 'hover' 
            },
            activeName:'many',
            manyTableData:[],
            onlyTableData:[],
            addDialogFormVisible:false,
            addForm:{
                attr_name:''
            },
            addFormRules:{
                attr_name:[
                  {required: true, message: '请输入参数名称', trigger: 'blur'}  
                ]
            },
            editDialogFormVisible:false,
            editForm:{},
            editFormRules:{
                attr_name:[
                  {required: true, message: '请输入参数名称', trigger: 'blur'}  
                ]
            },
        }
    },
    methods: {
        async getAllCateList(){
           const {data:res} = await this.$http.get('categories')
           if (res.meta.status !== 200) {
              return this.$message.error('商品分类获取失败！')
           }
           this.cateList = res.data
        },
        handleChange(){
            this.getParamsList()
        },
        handleClick(){
            this.getParamsList()
        },
        async getParamsList(){
            if (this.selectedKeys.length !== 3) {
               this.selectedKeys = []
               this.manyTableData = []
               this.onlyTableData = []
               return 
            }
            const {data:res} = await this.$http.get(`categories/${this.cateID}/attributes`,{params:{sel:this.activeName}})
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                item.inputVisible = false
                item.inputValue = ''
            });
            if (this.activeName == 'many') {
                this.manyTableData = res.data
            } else {
                this.onlyTableData = res.data
            }
        },
        addFormClose(){
            this.$refs.addFormRef.resetFields()
        },
        addFormShow(){
            this.addDialogFormVisible = true
        },
        addParams(){
            this.$refs.addFormRef.validate(async valid => {
                if(!valid) return
                const {data:res} = await this.$http.post(`categories/${this.cateID}/attributes`,{   attr_name:this.addForm.attr_name,
                attr_sel: this.activeName
                })
                this.addDialogFormVisible = false
                this.getParamsList()
                this.$message({
                type: 'success',
                message: '添加成功!'
                });
            })
        },
        editFormClose(){
            this.$refs.editFormRef.resetFields()
        },
       async showEditVisble(attr_id){
            const {data:res} = await this.$http.get(`categories/${this.cateID}/attributes/${attr_id}`,{
                params:{attr_sel:this.activeName}
            })
            if(res.meta.status !== 200){
                this.$message({
                    message: '请求参数失败',
                    type: 'error'
                });
            }
            this.editForm = res.data
            this.editDialogFormVisible = true
        },
        editParams(){
            this.$refs.editFormRef.validate(async valid => {
                if(!valid) return
                const {data:res} = await this.$http.put(`categories/${this.cateID}/attributes/${this.editForm.attr_id}`,{
                    attr_name:this.editForm.attr_name,
                    attr_sel:this.activeName
                })
                this.editDialogFormVisible = false
                this.getParamsList()
                this.$message({
                type: 'success',
                message: '修改成功!'
                });
            })
        },
        deteleParams(id){
            this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async() => {
            await this.$http.delete(`categories/${this.cateID}/attributes/${id}`)
            this.getParamsList()
            this.$message({
                type: 'success',
                message: '删除成功!'
            });
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
        },
        showInput(row) {
            row.inputVisible = true;
            this.$nextTick(() => {
            this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        handleInputConfirm(row) {
            let inputValue = row.inputValue;
            if (inputValue) {
            row.attr_vals.push(inputValue);
            }
            if(row.inputValue.trim().length !== 0) {
                this.saveAttrVals(row)
                row.inputVisible = false;
                row.inputValue = '';
                return
            }
            row.inputVisible = false;
            row.inputValue = '';
        },
        handleClose(i,row){
            row.attr_vals.splice(i,1);
            this.saveAttrVals(row)
        },
        async saveAttrVals(row){
            
            const {data:res} = await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`,{
                    attr_name:row.attr_name,
                    attr_sel:row.attr_sel,
                    attr_vals:row.attr_vals.join(' ')
                })
            if(res.meta.status !== 200){
                return this.$message({
                            message: '更新标签失败',
                            type: 'error'
                        });
            }
            this.$message({
                message: '更新标签成功',
                type: 'success'
            });
        }
    },
    created() {
        this.getAllCateList()
    },
    // 计算属性
    computed: {
        cateID(){
           return this.selectedKeys[2]
        },
        isBtnDisabled(){
            if(this.selectedKeys.length !== 3){
                return true
            }
            return false
        },
        titleText(){
            if (this.activeName == 'many') {
                return '动态参数'
            } else {
                return '静态属性'
            }
        }
    },
    
}
</script>

<style lang="less" scoped>
.cat_opt{
    margin: 15px 0;
}
.el-tag{
    margin: 10px;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
</style>